package com.work.lxykeeper.module.main;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.work.lxykeeper.R;
import com.work.lxykeeper.base.BaseActivity;
import com.work.lxykeeper.databinding.ActivityUpversionBinding;
import com.work.lxykeeper.view.SignDialog;

import java.io.File;

/**
 * Created by WZ on 2019/6/12.
 * description:更新新版本
 */
public class UpVersionActivity extends BaseActivity {
    private SignDialog signDialog;
    private String apkurl;
    private DownloadManager mDownloadManager;
    private long mId;
    private Dialog mDialog1;
    private ProgressBar mProgressBar;
    private TextView mPrecent;
    private String PACKAGE_NAME;
    private ActivityUpversionBinding binding;


    @Override
    protected View getLayoutView() {
        binding= ActivityUpversionBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        mTitleBar.titleMiddle.setText("下载应用");
        apkurl = getIntent().getStringExtra("url");
    }

    private void installApp() {
        //        VersionUpdateUtil.gotoUpdate(this, apkurl);
        //此处使用DownLoadManager开启下载任务
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkurl));
        // 下载过程和下载完成后通知栏有通知消息。
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE | DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("152彩票");
        request.setDescription("apk正在下载");
        //设置保存目录  /storage/emulated/0/Android/包名/files/Download
        request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "aly.apk");
        mId = mDownloadManager.enqueue(request);
        //注册内容观察者，实时显示进度
        MyContentObserver downloadChangeObserver = new MyContentObserver(null);
        getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, downloadChangeObserver);

        //广播监听下载完成
        listener(mId);
        //弹出进度条，先隐藏前一个dialog
        //显示进度的对话框
        mDialog1 = new Dialog(this, R.style.Theme_AppCompat_Dialog_Alert);
        View view = this.getLayoutInflater().inflate(R.layout.progress_dialog, null);
        mProgressBar = view.findViewById(R.id.pb);
        mPrecent = view.findViewById(R.id.tv_precent);
        mDialog1.setContentView(view);
        mDialog1.setCanceledOnTouchOutside(false);
        mDialog1.show();
    }

    @Override
    protected void initData() {
        installApp();
    }

    private void showUninstall() {
        signDialog = new SignDialog.Builder(this).setTitleText("卸载应用").setContentText("同时清理残余文件").setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signDialog.dismiss();
            }
        }).setRightOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signDialog.dismiss();
                //卸载应用
                unInstallApp();
            }

        }).create();
        signDialog.show();
    }

    private void unInstallApp() {
        //卸载
        Uri packageUri = Uri.parse("package:" + this.getPackageName());
        Intent intent = new Intent(Intent.ACTION_DELETE, packageUri);
        startActivity(intent);

    }


    private void listener(final long id) {
        //Toast.makeText(MainActivity.this,"XXXX",Toast.LENGTH_SHORT).show();
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long longExtra = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (id == longExtra) {
//                    Uri downloadUri = mDownloadManager.getUriForDownloadedFile(id);
                    Intent install = new Intent(Intent.ACTION_VIEW);
                    File apkFile = getExternalFilesDir("DownLoad/aly.apk");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri uriForFile = FileProvider.getUriForFile(context, "com.work.dyduser.fileprovider", apkFile);
                        install.setDataAndType(uriForFile, "application/vnd.android.package-archive");
                    } else {
                        install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                    }
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(install);
                    showUninstall();
                }
            }

        };

        registerReceiver(broadcastReceiver, intentFilter);
    }

    class MyContentObserver extends ContentObserver {

        public MyContentObserver(Handler handler) {
            super(handler);
        }


        @TargetApi(Build.VERSION_CODES.N)
        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(mId);
            DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                float progress = (float) Math.floor(percent * 100);
                mPrecent.setText(progress + "%");
                mProgressBar.setProgress((int) progress, true);
                if (progress == 100)
                    mDialog1.dismiss();
            }
        }

    }

}
